package dao;

import entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by Tiler on 2020/11/23
 */
@Repository
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<User> selectAllUsers() {
        //将数据库的一行映射到对象的属性上
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);

        List<User> users = jdbcTemplate.query("select * from user", rowMapper);

        /*
        List<User> users = new ArrayList<>();

        List<Map<String, Object>> maps = jdbcTemplate.queryForList("select * from user");

        for (Map<String, Object> map : maps) {
            User user = new User();

            user.setUid((Integer) map.get("uid"));
            user.setUsername((String) map.get("username"));
            user.setPassword((String) map.get("password"));
            user.setName((String) map.get("name"));
            user.setSex((String) map.get("sex"));
            user.setBirthday((Date) map.get("birthday"));

            users.add(user);
        }
        */

        return users;
    }

    @Override
    public Integer selectUserCount() {
        return jdbcTemplate.queryForObject("select count(*) from user", Integer.class);
    }

    @Override
    public User selectUserByUid(Integer uid) {
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);

        return jdbcTemplate.queryForObject("select * from user where uid = ?", rowMapper, uid);
    }

    @Override
    public Integer insertOneUser(User user) {
        String sql = "insert into user(username, password, name, sex, birthday) values(?, ?, ?, ?, ?)";

        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getName(), user.getSex(),
                user.getBirthday());
    }

    @Override
    public Integer updateOneUser(User user) {
        String sql = "update user set username = ?, password = ?, name = ?, sex = ?, birthday = ? where uid = ?";

        return jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getName(), user.getSex(),
                user.getBirthday(), user.getUid());
    }

    @Override
    public Integer deleteUserByUid(Integer uid) {
        return jdbcTemplate.update("delete from user where uid = ?", uid);
    }
}
